import axios from 'axios'

const http = axios.create({
  withCredentials: true,
  baseURL: process.env.BASE_API,
  headers: { 'X-Requested-with': 'XMLHttpRequest' }
})

http.interceptors.request.use(config => {
  config['url'] = encodeURI(config['url'])
  if (sessionStorage.getItem('token')) {
    config.headers['Authorization'] = `Bearer ${sessionStorage.getItem(
      'token'
    )}`
  }
  return config
})

http.interceptors.response.use(
  resp => {
    if (resp.data.code !== 0) {
      // global._vm.$message.error(resp.data.msg || '未知错误')
      // const error = new Error(resp.data.msg || '未知错误')
      const error = resp.data.msg || '未知错误'
      // error.response = resp
      return Promise.reject(error)
    }
    return resp
  },
  error => {
    if (error.response.status === 401) {
      global._vm.$message.error('登录已失效，请重新登录！')
      global._vm.$router.push('/login')
    } else if (error.response.status === 403) {
      global._vm.$message.error('您没有权限访问该功能！')
    }
    return Promise.reject(error)
  }
)

export default http
